package com.gugee.tiktok.data.consumer.blogger.core.main;

import com.gugee.tiktok.common.model.es.ESBlogger;
import com.gugee.tiktok.common.model.es.ESBloggerFansPortrait;
import com.gugee.tiktok.common.model.mysql.BloggerMain;
import com.gugee.tiktok.data.consumer.blogger.config.DataConsumerConfig;
import com.gugee.tiktok.data.consumer.blogger.core.service.AwemeClient;
import com.xiguaji.boot.toolkit.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: luolifeng
 * Date: 2020-10-14 19:34
 */
@Slf4j
@Component
public class ESSaveBloggerMain {

    private final String BLOGGER_INDEX = "blogger_main_idx";
    @Autowired
    RestHighLevelClient highLevelClient;

    @Autowired
    AwemeClient awemeClient;

    @Autowired
    DataConsumerConfig dataConsumerConfig;
    @Autowired
    ESBlogger.ESBloggerMapper esBloggerMapper;


    public void handle(List<BloggerMain> bloggers){
        long start = System.currentTimeMillis();
        List<ESBlogger> esbloggers = esBloggerMapper.mapper(bloggers);
        BulkRequest bulkRequest = new BulkRequest();
        esbloggers.forEach( b->{
            // refreshAweme(b);
            ESBloggerFansPortrait bloggerFansPortrait = getFansPortrait(b.getUid());

            if(null != bloggerFansPortrait){
                b.setFansPortraitUpdate(bloggerFansPortrait.getFansPortraitUpdate());
                b.setActiveDayDistribution(bloggerFansPortrait.getActiveDayDistribution());
                b.setActiveWeekDistribution(bloggerFansPortrait.getActiveWeekDistribution());
                b.setLanguageDistribution(bloggerFansPortrait.getLanguageDistribution());
                b.setRegionDistribution(bloggerFansPortrait.getRegionDistribution());
                b.setGenderDistribution(bloggerFansPortrait.getGenderDistribution());
                b.setAgeDistribution(bloggerFansPortrait.getAgeDistribution());
                b.setGenderDistributionMax(bloggerFansPortrait.getGenderDistributionMax());
                b.setLanguageDistributionMax(bloggerFansPortrait.getLanguageDistributionMax());
                b.setRegionDistributionMax(bloggerFansPortrait.getRegionDistributionMax());
                b.setAgeDistributionMax(bloggerFansPortrait.getAgeDistributionMax());
            }

            IndexRequest indexRequest = new IndexRequest(this.BLOGGER_INDEX);
            indexRequest.id(String.valueOf(b.getId()));
            indexRequest.source(JsonUtil.parseJson(b), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        try {
            val bulk = highLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES RefreshBlogger error",e);
        }

        if((System.currentTimeMillis()-start)/1000 >dataConsumerConfig.getDebugTimeLimit())
            log.info("ESSaveBloggerMainEventListener updateBloggerEs use time:"+(System.currentTimeMillis()-start)/1000+"s");

    }

    private ESBloggerFansPortrait getFansPortrait(long id) {
        ESBloggerFansPortrait bloggerFansPortrait = null;
        SearchRequest searchRequest = new SearchRequest(BLOGGER_INDEX);
        //构建搜索源对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("uid",id));
        //过滤条件 第一个要显示的字段,第二个不显示的
        searchSourceBuilder.fetchSource(new String[]{"fansPortraitUpdate","genderDistributionMax","languageDistributionMax","regionDistributionMax","ageDistributionMax","activeDayDistribution","activeWeekDistribution","languageDistribution","regionDistribution","genderDistribution","ageDistribution"},new String[]{});
        searchRequest.source(searchSourceBuilder);
        //执行搜索,向ES发起Http请求,获得结果对象

        try{
            SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            val hits = searchResponse.getHits().getHits();

            for (SearchHit hit : hits) {
                bloggerFansPortrait = JsonUtil.jsonParse(ESBloggerFansPortrait.class,hit.getSourceAsString());
            }
        }catch (Exception e){
            log.error("search ES FansPortrait ERROR",e);
        }

        return bloggerFansPortrait;


    }
}
